﻿using System;
using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;
using WindowsPhoneMvp.Events;

namespace WindowsPhoneMvp.Phone
{
    ///<summary>
    /// A base MvpUserControl
    ///</summary>
    public class MvpUserControl : UserControl, IView, IEventRoutingView
    {
        ///<summary>
        /// A load event that occurs when the view has been loaded into view
        ///</summary>
        public event EventHandler Load = delegate { };
        EventToPresenter IEventRoutingView.EventToPresenter { get; set; }

        bool throwExceptionIfNoPresenterBound;
        readonly bool registeredWithPageViewHost;

        /// <summary>
        /// Gets or sets whether the runtime should throw an exception if a presenter is not bound to this control.
        /// </summary>
        /// <value><c>true</c> if an exception should be thrown (default); otherwise, <c>false</c>.</value>
        public bool ThrowExceptionIfNoPresenterBound
        {
            get
            {
                return throwExceptionIfNoPresenterBound;
            }
            set
            {
                if (registeredWithPageViewHost)
                {
                    throw new InvalidOperationException("ThrowExceptionIfNoPresenterBound can only be set prior to the control's Init event. The best place to set it is in the control's constructor.");
                }
                throwExceptionIfNoPresenterBound = value;
            }
        }

        ///<summary>
        /// Instantiates a new MvpUserControl
        ///</summary>
        public MvpUserControl()
        {
            if (!DesignerProperties.IsInDesignTool)
            {
                ThrowExceptionIfNoPresenterBound = true;
                registeredWithPageViewHost = true;
                PageViewHost.Register(this);
                Loaded += MvpPhoneApplicationPageLoaded;
            }
        }

        void MvpPhoneApplicationPageLoaded(object sender, RoutedEventArgs e)
        {
            Load(sender, e);
            Loaded -= MvpPhoneApplicationPageLoaded;
        }

        protected void HandleRoutedEvent(object sender, RoutedEventArgs e)
        {
            var source = e.OriginalSource as UIElement;
        }
    }
}
